package com.tiancikeji.zaoke.app.dao.food.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.tiancikeji.zaoke.app.dao.food.FoodTagDao;
import com.tiancikeji.zaoke.app.model.food.FoodTag;

public class FoodTagsDaoImpl extends JdbcDaoSupport implements FoodTagDao{

	private static final String TABLE = "`zaoke`.`food_tags`";
	private static final String QUERY_VIEW = "`id`, `food_id`, `tag`, `add_userid`, `add_time`, `lastmod_userid`, `lastmod_time`";

	private List<FoodTag> _query(String sql) {
		List<FoodTag> tags = getJdbcTemplate().query(sql, new RowMapper<FoodTag>() {

			public FoodTag mapRow(ResultSet rs, int rowNum) throws SQLException {
				FoodTag tag = new FoodTag();
				tag.setId(rs.getLong("id"));
				tag.setFoodid(rs.getLong("food_id"));
				tag.setTag(rs.getString("tag"));
				tag.setAddUserid(rs.getLong("add_userid"));
				tag.setAddTime(rs.getDate("add_time"));
				tag.setLastmodUserid(rs.getLong("lastmod_userid"));
				tag.setLastmodTime(rs.getDate("lastmod_time"));
				return tag;
			}
		});
		return tags;
	}

	public List<FoodTag> getTagsByFoodIds(Set<Long> remainings) {
		String sql = "select " + QUERY_VIEW + " from " + TABLE + " where `food_id` in (";
		sql += StringUtils.join(remainings, ",");
		sql += ")";
		return _query(sql);
	}

	public List<FoodTag> getAllTags() {
		String sql = "select " + QUERY_VIEW + " from " + TABLE;
		return _query(sql);
	}
}
